<template>
  <a-spin :spinning="spinning != 0">
    <a-form :form="form"
            layout="horizontal"
            :hideRequiredMark="false"
            style="">
      <a-row class="grid-row">
        <a-col v-bind="colLayout2.cols" class="grid-col">
          <a-form-item :label="$t('m.system.httpconfig.entity.httpName')" :label-col="colLayout2.labelCol" :wrapper-col="colLayout2.wrapperCol">
            <a-input
              :disabled="disabledRules.httpName"
              placeholder=""
              type="text"
              v-decorator="['httpName', validatorRules.httpName]"
            />
          </a-form-item>
        </a-col>
        <a-col v-bind="colLayout2.cols" class="grid-col">
          <a-form-item :label="$t('m.system.httpconfig.entity.httpCode')" :label-col="colLayout2.labelCol" :wrapper-col="colLayout2.wrapperCol">
            <a-input
              :disabled="disabledRules.httpCode"
              placeholder=""
              type="text"
              v-decorator="['httpCode', validatorRules.httpCode]"
            />
          </a-form-item>
        </a-col>
        <a-col v-bind="colLayout2.fixed.cols" class="grid-col">
          <a-form-item :label="$t('m.system.httpconfig.entity.httpUrl')"  :label-col="colLayout2.fixed.labelCol" :wrapper-col="colLayout2.fixed.wrapperCol">
            <a-input
              :disabled="disabledRules.httpUrl"
              placeholder=""
              type="text"
              v-decorator="['httpUrl', validatorRules.httpUrl]"
            />
          </a-form-item>
        </a-col>
        <a-col v-bind="colLayout2.cols" class="grid-col">
          <a-form-item :label="$t('m.system.httpconfig.entity.httpMethod')" :label-col="colLayout2.labelCol" :wrapper-col="colLayout2.wrapperCol">
            <!--<a-radio-group
                    :disabled="disabledRules.httpMethod"
            v-decorator="['httpMethod', validatorRules.httpMethod]" button-style="solid"
            >

                    <a-radio-button value="GET">GET</a-radio-button>
                    <a-radio-button value="POST">POST</a-radio-button>
            </a-radio-group>-->
            <a-select
              :disabled="disabledRules.httpMethod"
              v-decorator="['httpMethod', validatorRules.httpMethod]"
              @change="httpMethodChange"
            >
              <a-select-option value="GET">GET</a-select-option>
              <a-select-option value="POST">POST</a-select-option>

            </a-select>

          </a-form-item>
        </a-col>
        <a-col v-bind="colLayout2.fixed.cols" class="grid-col">
          <a-form-item :label="$t('m.system.httpconfig.entity.httpHeader')" :label-col="colLayout2.fixed.labelCol" :wrapper-col="colLayout2.fixed.wrapperCol">
            <vxe-toolbar>
              <template #buttons>
                <a-button type="primary" icon="plus" @click="insertRow('header', subTableConfig.header.dataSource, {}, 'key')">{{ $t('m.common.button.add') }}</a-button>
                <span class="action-button-gap"></span>
                <a-button type="default" icon="minus" @click="deleteRow('header', subTableConfig.header.dataSource)">{{ $t('m.common.button.delete') }}</a-button>
                <a-tooltip style="padding-left: 10px;" :title="$t('m.system.httpconfig.other.exprTitle', ['${X-Access-Token}', '${userId}', '${loginName}', '${userName}', '${deptId}', '${deptCode}', '${deptName}', '${orgId}', '${orgCode}', '${orgName}'])">
                  <ych-icon type="question-circle"></ych-icon>
                </a-tooltip>
              </template>
            </vxe-toolbar>
            <vxe-table
              ref="header"
              border
              show-header-overflow
              show-overflow
              :header-cell-style="getHeaderCellStyle"
              :row-config="{isHover: true}"
              :edit-config="{trigger: 'click', mode: 'cell'}"
              :edit-rules="headerValidRules"
              :data="subTableConfig.header.dataSource">
              <vxe-column type="checkbox" width="60"></vxe-column>
              <vxe-column type="seq" :title="$t('m.common.label.number')" width="60"></vxe-column>
              <vxe-column field="key" title="key" :edit-render="{name: 'input'}"></vxe-column>
              <vxe-column field="value" title="value" :edit-render="{name: 'input'}"></vxe-column>
            </vxe-table>
          </a-form-item>
        </a-col>
        <a-col v-bind="colLayout2.cols" class="grid-col" v-show="httpMethod=='POST'">
          <a-form-item :label="$t('m.system.httpconfig.entity.inParameterType')" :label-col="colLayout2.labelCol" :wrapper-col="colLayout2.wrapperCol">
            <a-select
              :disabled="disabledRules.inParameterType"
              v-decorator="['inParameterType', validatorRules.inParameterType]"
              @change="inParameterTypeChange"
            >

              <a-select-option value="key-value">{{$t('m.system.httpconfig.entity.keyvalue')}}</a-select-option>
              <a-select-option value="json">JSON</a-select-option>

            </a-select>

          </a-form-item>
        </a-col>
        <a-col v-bind="colLayout2.fixed.cols" class="grid-col" v-show="httpMethod=='POST'">
          <a-form-item :label="$t('m.system.httpconfig.entity.inParameter')" :label-col="colLayout2.fixed.labelCol" :wrapper-col="colLayout2.fixed.wrapperCol">
            <a-textarea v-show="inParameterType=='json'"
                        :autoSize="{
                                minRows: 6,
                                maxRows: 8
                                }"
                        :disabled="disabledRules.inParameter"
                        :rows="4"
                        v-decorator="['inParameter', validatorRules.inParameter]"
            />
            <vxe-toolbar v-show="inParameterType=='key-value'">
              <template #buttons>
                <a-button type="primary" icon="plus" @click="insertRow('inParameter', subTableConfig.inParameter.dataSource, {}, 'key')">{{ $t('m.common.button.add') }}</a-button>
                <span class="action-button-gap"></span>
                <a-button type="default" icon="minus" @click="deleteRow('inParameter', subTableConfig.inParameter.dataSource)">{{ $t('m.common.button.delete') }}</a-button>
              </template>
            </vxe-toolbar>
            <vxe-table
              v-show="inParameterType=='key-value'"
              ref="inParameter"
              border
              show-header-overflow
              show-overflow
              :header-cell-style="getHeaderCellStyle"
              :edit-rules="inParameterValidRules"
              :row-config="{isHover: true}"
              :edit-config="{trigger: 'click', mode: 'cell'}"
              :data="subTableConfig.inParameter.dataSource">
              <vxe-column type="checkbox" width="60"></vxe-column>
              <vxe-column type="seq" :title="$t('m.common.label.number')" width="60"></vxe-column>
              <vxe-column field="key" title="key" :edit-render="{name: 'input'}"></vxe-column>
              <vxe-column field="value" title="value" :edit-render="{name: 'input'}"></vxe-column>
            </vxe-table>
          </a-form-item>
        </a-col>
        <!--<a-col v-bind="colLayout2.cols" class="grid-col">
          <a-form-item label="连接器类型" :label-col="colLayout2.labelCol" :wrapper-col="colLayout2.wrapperCol">
            <a-select
              :disabled="disabledRules.connentorId"
              v-decorator="['connentorId', validatorRules.connentorId]"
            >
              <a-select-option value="http-connector">http-connector</a-select-option>
            </a-select>

          </a-form-item>
        </a-col>-->

        <a-col v-bind="colLayout2.cols" class="grid-col">
          <a-form-item :label="$t('m.common.label.sort')" :label-col="colLayout2.labelCol" :wrapper-col="colLayout2.wrapperCol">
            <a-input-number
              style="width: 100%"
              :min="0"
              :max="999999999"
              :disabled="disabledRules.orderBy"
              :step="1"
              placeholder=""
              v-decorator="['orderBy', validatorRules.orderBy]"
            />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-spin>
</template>

<script>

import {FormMixin} from '@/mixins/FormMixin'
import {GardLayoutMixin} from '@/mixins/GardLayoutMixin'
import {getAction, httpAction} from '@/api/manage'
import YchConstant from "@/api/YchConstant";
import { duplicateCheck } from '@/api/api'

export default {
  name: "ActAppHttpFormModal",
  mixins: [FormMixin, GardLayoutMixin],
  data() {
    return {
      inParameterType: '',
      httpMethod: '',
      validatorRules: {
        httpName: {
          rules: [{ required: true, message: this.$t('m.system.httpconfig.verify.httpName') }]
        },
        httpCode: {
          rules: [{ required: true, message: this.$t('m.system.httpconfig.verify.httpCode') },{ validator: this.validateCode }]
        },
        httpUrl: {
          rules: [{ required: true, message: this.$t('m.system.httpconfig.verify.httpUrl') }]
        },
        httpMethod: {
          rules: []
        },
        inParameterType: {
          rules: []
        },
        inParameter: {
          rules: []
        },
        outParameter: {
          rules: []
        },
        groupId: {
          rules: []
        },
        orderBy: {
          rules: []
        },
      },
      headerValidRules: {
        key: [
          {required: true, message: this.$t('m.system.httpconfig.verify.header')},
        ],
      },
      inParameterValidRules: {
        key: [
          {required: true, message: this.$t('m.system.httpconfig.verify.inParameter')},
        ],
      },
      disabledRules: {
        httpName: false,
        httpCode: false,
        httpUrl: false,
        httpMethod: false,
        inParameterType: false,
        inParameter: false,
        outParameter: false,
        groupId: true,
        orderBy: false,
      },
      dictConfig: {},
      optionConfig: {},
      url: {
        queryById: YchConstant.PREFIX_EFORM + '/manage/actAppHttp/queryById',
        add: YchConstant.PREFIX_EFORM + "/manage/actAppHttp/add",
        edit: YchConstant.PREFIX_EFORM + "/manage/actAppHttp/edit",
      },
      subTableConfig:{
        header:{
          dataSource:[]
        },
        inParameter:{
          dataSource:[]
        }
      }
    }
  },
  methods: {
    validateCode(rule, value, callback) {
      let reg = new RegExp("[\\u4E00-\\u9FFF]+","g");
      if(reg.test(value)){
        callback(this.$t('m.common.tip.code_format'))
      }
      // 重复校验
      let params = {
        tableName: 'act_app_http',
        fieldName: 'http_code',
        fieldVal: value,
        dataId: this.model.id
      }
      duplicateCheck(params).then((res) => {
        if (res.success) {
          callback()
        } else {
          callback(res.message)
        }
      })
    },
    getHeaderCellStyle() {
      return "color:#666666;"
    },
    add(fks) {
      const model = {}
      if (fks) {
        fks.forEach(item => {
          model[item.colCode] = item.queryValue
        })
      }
      this.inParameterType = 'json'
      this.httpMethod = 'GET'
      model.inParameterType = 'json'
      model.httpMethod = 'GET'
      this.initFormData(model)
    },
    edit(id) {
      this.detail(id)
    },
    detail(id) {
      if (!this.url.queryById) {
        this.messageUtil.error(this.$t('m.system.httpconfig.other.qing-she-zhi-urlquerybyid-shu-xing'))
        return
      }
      this.spinning++
      getAction(this.url.queryById, {id: id}).then((res) => {
        if (res.success) {
          this.initFormData(res.result)
          this.inParameterType = res.result.inParameterType
          this.httpMethod = res.result.httpMethod
          if (res.result.headerList) {
            let id = 0;
            let headerList = res.result.headerList.map(item => {
              return {
                key: item.key,
                value: item.value,
                id: "header" + id++
              }
            })
            this.subTableConfig.header.dataSource = headerList
          }
          if (this.inParameterType == 'key-value') {
            if (res.result.inParameterList) {
              let id = 0;
              let inParameterList = res.result.inParameterList.map(item => {
                return {
                  key: item.key,
                  value: item.value,
                  id: "inParameter" + id++
                }
              })
              this.subTableConfig.inParameter.dataSource = inParameterList
            }
          }

        } else {
          this.messageUtil.warning(res.message)
        }
      }).finally(() => {
        this.spinning--
      })
    },
    validListRepeat(list) {
      for (let i = 0; i < list.length - 1; i++) {
        for (let j = i + 1; j < list.length; j++) {
          if (list[i].key == list[j].key) {
            return true
          }
        }
      }
      return false
    },
    async beforeSave(formData) {
      let that = this
      if (!formData.connentorId) {
        formData.connentorId = 'http-connector'
      }
      if (this.subTableConfig) {
        let subTableRef = Object.keys(this.subTableConfig);
        for(let i=0;i<subTableRef.length;i++){
          if (subTableRef[i]=='inParameter' && formData.inParameterType == 'json') {
            continue
          }
          let $subTable = that.$refs[subTableRef[i]]
          if(this.subTableConfig[subTableRef[i]].dataSource && this.subTableConfig[subTableRef[i]].dataSource.length>0){
            const subTableValues = await this.getTableDataSource($subTable, this.subTableConfig[subTableRef[i]].dataSource);
            if(subTableValues==false){
              return
            }else{
              if (this.validListRepeat(subTableValues)) {
                this.messageUtil.warning(subTableRef[i]=='header'?this.$t('m.system.httpconfig.verify.header_repeat'):this.$t('m.system.httpconfig.verify.inParameter_repeat'))
                return
              }
              formData[subTableRef[i] + 'List'] = subTableValues
            }
          }else{
            formData[subTableRef[i] + 'List'] = []
          }

        }
      }
      return formData;
    },
    inParameterTypeChange(e) {
      this.inParameterType = e
    },
    httpMethodChange(e) {
      this.httpMethod = e
    }
  },
}
</script>
